import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_chubao/config/app_config.dart';
import 'package:flutter_chubao/config/app_manger_user.dart';
import 'package:flutter_chubao/models/model_app_config.dart';
import 'package:flutter_chubao/models/model_user.dart';
import 'package:flutter_chubao/pages/home/app_home/app_home_view.dart';
import 'package:flutter_chubao/pages/mine/app_mine/app_mine_view.dart';
import 'package:flutter_chubao/route/app_route_name.dart';
import 'package:flutter_chubao/tools/app_log.dart';
import 'package:flutter_chubao/tools/app_tool_toast.dart';
import 'package:flutter_chubao/tools/tool_app/app_dio_client.dart';
import 'package:flutter_chubao/tools/tool_app/app_dio_response.dart';
import 'package:flutter_chubao/widgets/app_alert_dialog.dart';
import 'package:flutter_gromore/callback/gromore_splash_callback.dart';
import 'package:flutter_gromore/config/gromore_splash_config.dart';
import 'package:flutter_gromore/flutter_gromore.dart';
// import 'package:flutter_unionad/flutter_unionad.dart';
import 'package:flutter_chubao/tools/shared/app_shared.dart';
import 'package:get/get.dart';
import 'package:uuid/uuid.dart';

import 'app_main_state.dart';

/// @description:
/// @author
/// @date: 2023-12-13 10:16:48
class AppMainLogic extends GetxController {
  final state = AppMainState();
  clickPage(int index) {
    if (index != state.tabIndex) {
      state.tabIndex = index;
      update();
    }
  }

  getTabbarDataSource() {
    state.tabPage.clear();

    state.tabPage = [AppHomePage(), AppMinePage()];
  }

  // Future<bool> getIsFirstLaunch() async {
  //   state.isNotFrist = await SSUtilShared.getBool(SSUtilConstant.isFirstLaunch);
  //   SSUtilShared.setBool(SSUtilConstant.isFirstLaunch, true);
  //   return state.isNotFrist;
  // }
  // againCheckNet() async {
  //   SSUtilToast.showLoading();

  //   var connectivityResult = await (Connectivity().checkConnectivity());
  //   SSUtilToast.dismiss();
  //   if (connectivityResult == ConnectivityResult.none) {
  //     SSUtilToast.showToast('当前设备无网络');
  //   } else {
  //     // state.isNet = await getInitServerTime();
  //     // if (state.isNet == true) {
  //     //  setState(() {
  //     state.isNet = true;
  //     update();
  //     // });
  //     // }
  //   }
  // }

  Future getNetState({bool showToast = false}) async {
    // Connectivity
    if (showToast == false) {
      await getIsFirstLaunch();
    }
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.none) {
      if (showToast) {
        AppToolToast.showToast('当前设备无网络');
      }
      if (state.connectStream == null) {
        state.connectStream = Connectivity().onConnectivityChanged;
        state.connectStream?.listen((ConnectivityResult result) async {
          if (state.isNet == false) {
            if (result != ConnectivityResult.none) {
              state.isNet = await getInitServerTime();
              update();
            }
          }
        });
      }
    } else {
      state.isNet = await getInitServerTime();
    }

    if (AppManagerUser.isLogin()) {
      getTabbarDataSource();
    }
    // getTabbarDataSource();
    return state.isNet;
  }

  /// 展示开屏广告
  Future<void> showSplashAd() async {
    await FlutterGromore.showSplashAd(
        config: GromoreSplashConfig(
            adUnitId:
                (AppConfig.configEntity?.spread ?? []).first?.adCodeId ?? '',
            logo: "launch_image"),
        callback: GromoreSplashCallback(onAdShow: () {
          print("callback --- onAdShow");
        }));

    print("showSplashAd success");
  }

  Future getLogin() async {
    String uuid = '';
    if (AppSharedPro.getString('uuid').isNotEmpty) {
      uuid = AppSharedPro.getString('uuid');
    } else {
      uuid = Uuid().v1();
    }
    AppDioResponse response = await AppDioClient.post(
        '/mini/chubao/device_login',
        data: {'account': uuid});
    if (response.ok) {
      AppSharedPro.setString('uuid', uuid);
      AppDioClient.appToken = response.data['token'];
      await getUserInfo(response.data['token']);
      //  AppManagerUser.getPostUserInfo();
    }
  }

  Future getUserInfo(String token) async {
    AppDioClient.appToken = token;
    UserEntity? userInfoEntity = await AppManagerUser.getPostUserInfo();

    if (userInfoEntity != null) {
      userInfoEntity.token = token;
      await AppManagerUser.userLogin(userInfoEntity);
    } else {
      AppDioClient.appToken = '';
    }
  }

  getInitServerTime() async {
    // /mini/chubao/ad/config

    AppDioResponse response = await AppDioClient.post(
      '/mini/chubao/ad/config',
    );
    if (response.ok) {
      if (state.initSDK == false) {
        AppConfigEntity configEntity = AppConfigEntity.fromJson(response.data);
        AppConfig.configEntity = configEntity;
        state.initSDK = await FlutterGromore.initSDK(
            appId: AppConfig.configEntity?.appId ?? '',
            appName: "厨宝",
            debug: kDebugMode,
            useMediation: true);
        await showSplashAd();
      }
      await AppManagerUser.initStorage();

      if (AppManagerUser.isLogin() == false) {
        await getLogin();
        // await AppManagerUser.getPostUserInfo();
      }
    }

    return response.ok;
  }
  // AppDioClient.post(uri)
  // AppDioResponse response = await AppDioClient.get(
  //   'dispose',
  // );
  // // SSHttpResponse response = await HttpClient.get('/app/config/app');
  // if (response.ok) {
  //   // Get.find<SSControllerApp>()
  //   //     .updateAppInfo(ModelAppInfoEntity.fromJson(response.data));
  //   //   // SSConfigApp.appConfigLists.clear();
  //   //   // response.data.forEach((element) {
  //   //   //   ModelAppConfigEntity configEntity =
  //   //   //       ModelAppConfigEntity.fromJson(element);
  //   //   //   SSConfigApp.appConfigLists.add(configEntity);
  //   //   // });
  //   return true;
  // }
  // return true;
  // return response.ok;
  // }

  Future<bool> getIsFirstLaunch() async {
    await Future.delayed(const Duration(milliseconds: 500));
    state.isNotFrist = AppSharedPro.getBool('isFirstLaunch');
    if (state.isNotFrist == false) {
      // showDialog(context: Get.context!, builder: )
      await Get.dialog(
          APPAlertDialog(
              titStr: '服务协议和隐私政策',
              infoWidet: RichText(
                  text: TextSpan(children: [
                const TextSpan(
                  text:
                      '    请你务必审核阅读、充分理解服务协议和隐私政策的各项条款，包括但不限于：为了更好的想你提供服务，我们需要手机你的设备标识、操作日志等信息用于分析、优化应用性能及体验。\n',
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xff333333),
                  ),
                ),
                const TextSpan(
                  text: '    你可阅读《注册协议》和《隐私政策》链接详细信息。如果你同意，请点击下面按钮开始接受我们的服务',
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xff333333),
                  ),
                ),
                TextSpan(
                  text: '《注册协议》',
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Get.toNamed(AppRouteName.appWebPage, arguments: {
                        'title': '注册协议',
                        'url':
                            'https://miniapi.dev.cdzjzx.com/mini/protocol_html?file=register'
                      });
                    },
                  style: const TextStyle(
                    fontSize: 14,
                    color: Color(0xff4C75FF),
                  ),
                ),
                const TextSpan(
                  text: '和',
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xff333333),
                  ),
                ),
                TextSpan(
                  text: '《隐私协议》',
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Get.toNamed(AppRouteName.appWebPage, arguments: {
                        'title': '隐私协议',
                        'url':
                            'https://miniapi.dev.cdzjzx.com/mini/protocol_html?file=yinsi'
                      });
                    },
                  style: const TextStyle(
                    fontSize: 14,
                    color: Color(0xff4C75FF),
                  ),
                ),
                const TextSpan(
                  text: '了解详细信息。如果你同意，请点击下面按钮开始接受我们的服务',
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xff333333),
                  ),
                )
              ])),
              infoStr: '',
              leftStr: '我不同意',
              rightStr: '同意',
              actionBtns: (index) {
                if (index == 0) {
                  exit(0);
                } else {
                  AppSharedPro.setBool('isFirstLaunch', true);
                  // JFUtilShared.setBool(JFUtilConstant.isFirstLaunch, true);
                }
                return true;
              }),
          barrierDismissible: false);
    }
    return state.isNotFrist;
  }

  // Future getUserInfo() async {
  //   if (AppManagerUser.isLogin()) {
  //     AppManagerUser.getPostUserInfo();
  //   }
  // }

  splashAdView() async {
    // DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    // AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    // androidInfo.devic
//     androidInfo.
// // androidInfo.id
//     final deviceInfoPlugin = DeviceInfoPlugin();
//     final deviceInfo1 = await deviceInfoPlugin.deviceInfo;
    // deviceInfo1.
// deviceInfo1.data

    // DLog('Running on ${deviceInfo1.data}'); // e.g. "Moto G (4)"
  }

  @override
  void onInit() {
    super.onInit();
    // splashAdView();

    state.netFuture = getNetState();
  }
}
